﻿using AliIotLib;
using IServices;
using Jil;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using WebApplication.Models;
using YL.Core.Dto;
using YL.Core.Entity;
using YL.Core.Entity.Fluent.Validation;
using YL.NetCore.Attributes;
using YL.NetCore.NetCoreApp;
using YL.Utils.Extensions;
using YL.Utils.Json;
using YL.Utils.Pub;
using YL.Utils.Table;

namespace Method.SmartMeter.Controllers
{
    public class DeviceInfoController : BaseController
    {
        private readonly IMeter_DeviceInfoServices _deviceInfoServices;
        private readonly IIotDeviceManager _aliIotDeviceManager;

        public DeviceInfoController(IMeter_DeviceInfoServices deviceInfoServices, IIotDeviceManager iotDeviceManager)
        {
            _deviceInfoServices = deviceInfoServices;
            _aliIotDeviceManager = iotDeviceManager;
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 电表注册 Index
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [CheckMenu]
        public IActionResult RegisterIndex()
        {
            return View();
        }

        [HttpPost]
        [OperationLog(LogType = LogType.select)]
        public ContentResult List([FromForm]Bootstrap.BootstrapParams bootstrap)
        {
            var sd = _deviceInfoServices.PageList(bootstrap, UserDtoCache.UserId);
            return Content(sd);
        }

        /// <summary>
        /// 获取电表注册列表
        /// </summary>
        /// <param name="bootstrap"></param>
        /// <returns></returns>
        [HttpPost]
        [OperationLog(LogType = LogType.select)]
        public ContentResult RegisterList([FromForm]Bootstrap.BootstrapParams bootstrap)
        {
            var sd = _deviceInfoServices.PageRegisterList(bootstrap, UserDtoCache.UserId);
            return Content(sd);
        }

        [HttpGet]
        public IActionResult Add(string id)
        {
            DeviceInfo client = new DeviceInfo();
            if (id.IsEmpty())
            {
                return View(client);
            }
            else
            {
                client = _deviceInfoServices.QueryableToEntity(c => c.DeviceId == SqlFunc.ToInt64(id));
                return View(client);
            }
        }

        [HttpGet]
        public IActionResult RegisterAdd(string id)
        {
            DeviceInfo client = new DeviceInfo();
            if (id.IsEmpty())
            {
                return View(client);
            }
            else
            {
                client = _deviceInfoServices.QueryableToEntity(c => c.DeviceId == SqlFunc.ToInt64(id));
                return View(client);
            }
        }

        [HttpPost]
        [FilterXss]
        [OperationLog(LogType = LogType.addOrUpdate)]
        public IActionResult AddOrUpdate([FromForm]DeviceInfo deviceInfo, [FromForm]string id)
        {
            //var validator = new MeterDeviceInfoFluent();
            //var results = validator.Validate(deviceInfo);
            //var success = results.IsValid;
            //if (!success)
            //{
            //    string msg = results.Errors.Aggregate("", (current, item) => (item.ErrorMessage + "</br>"));
            //    return BootJsonH((PubEnum.Failed.ToInt32(), msg));
            //}
            if (id.IsEmptyZero())
            {
                if (_deviceInfoServices.IsAny(c => c.DeviceSerialNum == deviceInfo.DeviceSerialNum))
                {
                    return BootJsonH((false, PubConst.Device1));
                }
                if (deviceInfo.DeviceId <= 0)
                {
                    AliIotRegisterDevice aliIotDeviceInfo = _aliIotDeviceManager.RegisterDevice(deviceInfo.DeviceSerialNum);//向阿里平台注册产品
                    if (aliIotDeviceInfo != null)
                    {
                        deviceInfo.AliDeviceName = aliIotDeviceInfo.DeviceName;
                        deviceInfo.AliDeviceSecret = aliIotDeviceInfo.DeviceSecret;
                        deviceInfo.AliProductKey = aliIotDeviceInfo.ProductKey;
                        deviceInfo.AliIotId = aliIotDeviceInfo.IotId;
                    }
                    else
                    {
                        return BootJsonH((PubEnum.Failed.ToInt32(), "阿里平台注册失败"));
                    }
                }

                deviceInfo.UserId = UserDtoCache.UserId;//获取当前的用户id
                bool flag = _deviceInfoServices.Insert(deviceInfo);
                return BootJsonH(flag ? (flag, PubConst.Add1) : (flag, PubConst.Add2));
            }
            else
            {
                deviceInfo.DeviceId = id.ToInt32();
                if (deviceInfo.ClientId > 0 && !string.IsNullOrEmpty(deviceInfo.DeviceName))
                {
                    deviceInfo.ModifiedBy = UserDtoCache.UserId;
                    deviceInfo.ModifiedDate = DateTime.Now;
                }
                var flag = _deviceInfoServices.Update(deviceInfo);
                return BootJsonH(flag ? (flag, PubConst.Update1) : (flag, PubConst.Update2));
            }
        }

        [HttpPost]
        [FilterXss]
        [OperationLog(LogType = LogType.addOrUpdate)]
        public IActionResult AddOrUpdate1([FromForm]DeviceInfo deviceInfo)
        {
            if (deviceInfo.DeviceId > 0)
            {
                if (deviceInfo.ClientId > 0 && !string.IsNullOrEmpty(deviceInfo.DeviceName))
                {
                    deviceInfo.ModifiedBy = UserDtoCache.UserId;
                    deviceInfo.ModifiedDate = DateTime.Now;
                }
                var flag = _deviceInfoServices.UpdateDeviceInfo(deviceInfo);
                return BootJsonH(flag ? (flag, PubConst.Update1) : (flag, PubConst.Update2));
            }
            return BootJsonH((false, PubConst.Update2));
        }


        [HttpGet]
        [OperationLog(LogType.delete)]
        public IActionResult Delete(string id)
        {
            var device = _deviceInfoServices.QueryableToEntity(x => x.DeviceId == id.ToInt32());
            if (device != null)
            {
                bool res = _aliIotDeviceManager.DeleteDevice(device.AliDeviceName);//删除阿里物联网平台设备
                if (res)
                {
                    var flag = _deviceInfoServices.Delete(x => x.DeviceId == id.ToInt64());
                    return BootJsonH(flag ? (flag, PubConst.Delete1) : (flag, PubConst.Delete2));
                }
            }
            return BootJsonH((PubEnum.Failed.ToInt32(), "设备删除失败"));
        }

        /// <summary>
        /// 获取用户导入的Excel表格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Import(IFormFile excelfile)
        {
            var res = new ResultModel();
            res.Message = "上传成功";
            res.Result = ResultType.Success.ToString();

            try
            {
                var files = Request.Form.Files;
                if (files?.Count > 0)
                {
                    IWorkbook wk = null;
                    var file = files[0];
                    MemoryStream fileStream = new MemoryStream();
                    file.CopyTo(fileStream);
                    fileStream.Position = 0;
                    string extension = Path.GetExtension(file.FileName);
                    if (extension.ToUpper().Equals(".XLS"))
                    {
                        wk = new HSSFWorkbook(fileStream);
                    }
                    else if (extension.ToUpper().Equals(".XLSX"))
                    {
                        wk = new XSSFWorkbook(fileStream);
                    }
                    fileStream.Close();

                    var sheetsNum = wk.NumberOfSheets;
                    if (sheetsNum < 1)
                    {
                        res.Message = "无sheet内容";
                        res.Result = ResultType.Warning.ToString();
                    }
                    else
                    {
                        ISheet sheet = wk.GetSheetAt(0); //取Excel中第一个Sheet中的内容

                        IRow rowHeader = sheet?.GetRow(0); //表头
                        var rowNum = sheet.LastRowNum; //当前表的总行数
                        var flag = false;
                        for (var i = 1; i <= rowNum; i++)
                        {
                            var getItemRow = sheet?.GetRow(i); //获得每行数据
                            if (getItemRow?.Cells?.Count() == 5)
                            {
                                flag = true;
                                DeviceInfo deviceInfo = new DeviceInfo();
                                deviceInfo.DeviceType = getItemRow?.Cells[0]?.ToString();
                                deviceInfo.DeviceSerialNum = getItemRow?.Cells[1]?.ToString();
                                deviceInfo.DeviceIp = getItemRow?.Cells[2]?.ToString();
                                if (int.TryParse(getItemRow?.Cells[3]?.ToString(), out int p))
                                {
                                    deviceInfo.DeviceBatch = int.Parse(getItemRow?.Cells[3].ToString());
                                }
                                deviceInfo.Description = getItemRow?.Cells[4]?.ToString();
                                var isRes = AddOrUpdate(deviceInfo, "0"); //插入数据
                            }
                        }
                        if (flag == false)
                        {
                            res.Message = "Excel内容为空!";
                            res.Result = ResultType.Warning.ToString();
                        }

                    }


                }
                else
                {
                    res.Message = "无文件";
                    res.Result = ResultType.Warning.ToString();
                }
            }
            catch (Exception e)
            {
                res.Message = e.Message;
                res.Result = ResultType.Error.ToString();
                //throw;
            }

            return JSON.Serialize(res);
        }

    }
}